package com.cn.dim.utils;

import java.beans.PropertyDescriptor;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.Security;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.DynaProperty;
import org.apache.commons.codec.digest.DigestUtils;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.apache.commons.lang.StringUtils;

public class BaseUtil {

	private static final BeanUtilsBean bean = BeanUtilsBean.getInstance();

	 public static String getIpAddr(HttpServletRequest request) {      
         String ip = request.getHeader("x-forwarded-for");      
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {      
            ip = request.getHeader("Proxy-Client-IP");      
        }      
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {      
            ip = request.getHeader("WL-Proxy-Client-IP");      
         }      
       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {      
             ip = request.getRemoteAddr();      
        }      
       return ip;      
  }
	   public static boolean useList(String[] arr, String targetValue) {
		    return Arrays.asList(arr).contains(targetValue);
	   }
	 
	 public static String jiami(String args) throws UnsupportedEncodingException {  
	    	//添加新安全算法,如果用JCE就要把它添加进去  
	    	byte[] enk = hex("zeromike");//用户名  
	    	Security.addProvider(new com.sun.crypto.provider.SunJCE());  
	    	String password = args;//密码  
	    	byte[] encoded = encryptMode(enk,password.getBytes());  
	    	String pword = Base64.encode(encoded);   
	    	pword=URLEncoder.encode(pword,"UTF-8");
	    	   
	    	return pword;
	    }
	    public static String jiemi(String args) throws UnsupportedEncodingException {  
	    	if(args.indexOf("+")<0){
	    	args=URLDecoder.decode(args,"UTF-8");
	    	}
	    	//添加新安全算法,如果用JCE就要把它添加进去  
	    	byte[] enk = hex("zeromike");//用户名  
	    	Security.addProvider(new com.sun.crypto.provider.SunJCE());  
	    	  byte[] reqPassword = Base64.decode(args);  
	          byte[] srcBytes = decryptMode(enk,reqPassword);  
	          return  (new String(srcBytes));
	    }
	    
	    public static byte[] hex(String username){  
	        String key = "test";//关键字  
	        String f = DigestUtils.md5Hex(username+key);  
	        byte[] bkeys = new String(f).getBytes();  
	        byte[] enk = new byte[24];  
	        for (int i=0;i<24;i++){  
	            enk[i] = bkeys[i];  
	        }  
	        return enk;  
	    }  
	    private static final String Algorithm = "DESede";
	    public static byte[] decryptMode(byte[] keybyte,byte[] src){  
	        try {  
	            //生成密钥  
	            SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);  
	            //解密  
	            Cipher c1 = Cipher.getInstance(Algorithm);  
	            c1.init(Cipher.DECRYPT_MODE, deskey);  
	            return c1.doFinal(src);  
	        } catch (java.security.NoSuchAlgorithmException e1) {  
	            // TODO: handle exception  
	            e1.printStackTrace();  
	        }catch(javax.crypto.NoSuchPaddingException e2){  
	            e2.printStackTrace();  
	        }catch(java.lang.Exception e3){  
	            e3.printStackTrace();  
	        }  
	        return null;          
	    } 
	    
	    //keybyte为加密密钥，长度为24字节      
	    //src为被加密的数据缓冲区（源）  
	    public static byte[] encryptMode(byte[] keybyte,byte[] src){  
	         try {  
	            //生成密钥  
	            SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);  
	            //加密  
	            Cipher c1 = Cipher.getInstance(Algorithm);  
	            c1.init(Cipher.ENCRYPT_MODE, deskey);  
	            return c1.doFinal(src);//在单一方面的加密或解密  
	        } catch (java.security.NoSuchAlgorithmException e1) {  
	            // TODO: handle exception  
	             e1.printStackTrace();  
	        }catch(javax.crypto.NoSuchPaddingException e2){  
	            e2.printStackTrace();  
	        }catch(java.lang.Exception e3){  
	            e3.printStackTrace();  
	        }  
	        return null;  
	    }  
	    
	    /** 随机数。 */
	    private static int serial = 0;

	    /** 随机数最大值。 */
	    private static final int MAX_SERIAL = 999;

	    /** 随机数长度。 */
	    private static final int SEQUENCE_LENTH = 12;
	    public static synchronized String makeUUID() {
	    	
	        StringBuffer ret = new StringBuffer();
	        SimpleDateFormat dfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
	        dfDate.setLenient(false);
	        ret.append(dfDate.format((new GregorianCalendar()).getTime()));     
	        DecimalFormat dfNum = new DecimalFormat("000");
	        ret.append(dfNum.format(serial++));
	        if (serial > MAX_SERIAL) {
	            serial = 0;
	        }
	        UUID uuid = UUID.randomUUID();
	        ret.append(uuid.toString().replace("-", "").subSequence(0, SEQUENCE_LENTH));

	        return ret.toString();
	    }

	    public static synchronized String selfMakeUUID() {
	        String s = UUID.randomUUID().toString();
	        String value = s.substring(0, 8) + s.substring(9, 13) + s.substring(14, 18) + s.substring(19, 23) + s.substring(24);
	        return value;
	    }

	    public static boolean isEmptyOrNull(String str) {
	        boolean isEmptyOrNull = true;
	        if (str != null && str.length() != 0) {
	            isEmptyOrNull = false;
	        }
	        return isEmptyOrNull;
	    }
	    
		
		
		public static String transTime(String time){
			String ti="";
			int h=time.indexOf("时");
			if(h>0){
				ti=time.substring(0,h);
				h+=1;
			}else{
				ti="00";
				h=0;
			}
			ti+=":";
			int m=time.indexOf("分");
			if(m>0){
				ti+=time.substring(h,m);
				m+=1;
			}else{
				ti+="00";
				m=0;
			}
			ti+=":";
			int s=time.indexOf("秒");
			if(s>0){
				ti+=time.substring(m,s);
			}else{
				ti+="00";
			}
			return ti;
		}
	    public static void main(String[] args) {
	    	String transTime = transTime("40秒");
	    	System.out.println(transTime);
		}

	public static void copyNonNullProperties(Object dest, Object orig)
	{
		copyProperties(dest, orig, false,null);
	}
	private static void copyProperties(Object dest, Object orig, boolean copyNulls,String split)
	{
		if (dest == null)
			throw new IllegalArgumentException("No destination bean specified");
		if (orig == null)
			throw new IllegalArgumentException("No origin bean specified");
		if ((orig instanceof DynaBean))
		{
			DynaProperty[] origDescriptors = ((DynaBean)orig).getDynaClass().getDynaProperties();
			for (int i = 0; i < origDescriptors.length; i++)
			{
				String name = origDescriptors[i].getName();
				String dname = getName(name,split);
				if (!bean.getPropertyUtils().isWriteable(dest, dname))
					continue;
				Object value = ((DynaBean)orig).get(name);
				try
				{
					if ((value != null) || (copyNulls))
						bean.copyProperty(dest, dname, value);
				}
				catch (Exception localException) {
				}
			}
		}
		else if ((orig instanceof Map))
		{
			Iterator names = ((Map)orig).keySet().iterator();

			while (names.hasNext())
			{
				String name = (String)names.next();
				String dname = getName(name,split);
				if (!bean.getPropertyUtils().isWriteable(dest, dname))
					continue;
				Object value = ((Map)orig).get(name);
				try
				{
					if ((value != null) || (copyNulls))
						bean.copyProperty(dest, dname, value);
				}
				catch (Exception localException1)
				{
				}
			}
		}
		else{
			PropertyDescriptor[] origDescriptors = bean.getPropertyUtils().getPropertyDescriptors(orig);
			for (int i = 0; i < origDescriptors.length; i++)
			{
				String name = origDescriptors[i].getName();
				String dname = getName(name,split);
				if (("class".equals(name)) || (!bean.getPropertyUtils().isReadable(orig, name)) || (!bean.getPropertyUtils().isWriteable(dest, dname)))
					continue;
				try
				{
					Object value = bean.getPropertyUtils().getSimpleProperty(orig, name);
					if ((value != null) || (copyNulls))
						bean.copyProperty(dest, dname, value);
				}
				catch (Exception localException2)
				{
				}
			}
		}
	}

	private static String getName(String name,String split){
		if(StringUtils.isBlank(split)){
			return name;
		}
		String[] names=name.split(split);
		String result=name;
		if(names.length>1){
			result=names[0];
			for(int i=1;i<names.length;i++){
				if(result.length()==1&&i==1){
					result+=names[i];
				}else{
					result+=names[i].substring(0,1).toUpperCase()+names[i].substring(1,names[i].length());
				}
			}
		}
		return result;
	}
}
